﻿using System;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Xml.Serialization;

namespace Wx.Sdk.Utils
{
    internal static class XmlHelper
    {
        /// <summary>
        /// 将实体转换成xml字符串
        /// </summary>
        /// <returns>The xml.</returns>
        /// <param name="t">T.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        //public static string ToXml<T>(T t) where T : class,new()
        //{
        //    t = t ?? new T();
        //    using (MemoryStream Stream = new MemoryStream())
        //    {
        //        XmlSerializer xml = new XmlSerializer(typeof(T));
        //        //序列化对象
        //        xml.Serialize(Stream, t);
        //        Stream.Position = 0;
        //        StreamReader sr = new StreamReader(Stream);
        //        string str = sr.ReadToEnd();
        //        return str;
        //    }
        //}

        /// <summary>
        /// 将实体转换成xml字符串
        /// </summary>
        /// <returns>The xml.</returns>
        /// <param name="t">T.</param>
        public static string ToXml<T>(T t) where T : class, new()
        {
            t = t ?? new T();
            XElement xele = new XElement(
                "xml",
                 t.GetType().GetProperties().Where(x=>x.GetValue(t)!=null).Select(x=>
                     new XElement(x.Name, x.GetValue(t)))
                );
            return xele.ToString();
        }
        /// <summary>
        /// 将字符串转换成实体
        /// </summary>
        /// <returns>The object.</returns>
        /// <param name="xml">Xml.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public static T ToObject<T>(string xml) where T : class,new()
        {
            var t = new T();
            if (xml.IsNull())
            {
                return t;
            }
            //将根替换
            xml = xml.Replace("<xml>", $"<{t.GetType().Name}>").Replace("</xml>", $"</{t.GetType().Name}>");
            xml = xml.Replace("<root>", $"<{t.GetType().Name}>").Replace("</root>", $"</{t.GetType().Name}>");
            using (var sr = new StringReader(xml))
            {
                XmlSerializer xmldes = new XmlSerializer(typeof(T));
                t = xmldes.Deserialize(sr) as T;
            }
            return t;
        }
    }
}
